package readers;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

import org.apache.log4j.Logger;

import uci.rt.ccr.engine.reader.CcrConfigReader;
import uci.rt.ccr1c.cfg.domain.CcrConfigGeneratorConfig;
import uci.rt.ccr1c.engine.matrix.Mat;
import uci.rt.ccr1c.engine.reader.GridPointFileReader;
import uci.rt.ccr1c.engine.reader.TextFileReader;
import uci.rt.ccr1c.engine.sheet.Sheet;
import uci.rt.ccr1c.scentrans.domain.GridPoint;
import uci.rt.pricing.date.calendar.CalendarException;
import uci.utils.DateFormatter;
import uci.utils.RunningTime;
import uci.utils.config.ConfigurationData;
import uci.utils.config.ReplaceUtils;
import uci.utils.files.FileParserException;

public class ScenarioBinFileExtractor
{

	private String pathIn;
	private String pathOut;
	private Date aod;
	private String filter;
	private String[] rfFilter;
		private Logger log;
	

	public ScenarioBinFileExtractor(String pathIn, String pathOut, Date aod, String filter)
	{
		this.log = Logger.getLogger(this.getClass());
		this.pathIn=pathIn;
		this.pathOut=pathOut;
		this.aod=aod;
		this.filter=filter;
	}

	/**
	 * @param args
	 * @throws FileParserException 
	 * @throws IOException 
	 * @throws InterruptedException 
	 * @throws CalendarException 
	 */
	public static void main(String[] args) throws IOException, FileParserException, InterruptedException, CalendarException
	{

		ConfigurationData cfg = ConfigurationData.getInstance();
		cfg.defaultSetup(args);
		Logger log = Logger.getRootLogger();

		log.info("Retrieve AOD");
		Date aod = cfg.getDate("AOD", null);

		if (aod == null)
			throw new IllegalArgumentException("AOD is missing");
		log.info("AOD = " + DateFormatter.format(aod));

		log.info("AOD=" + aod);

		String pathIn=cfg.getString("PATH_IN","");
		String pathOut=cfg.getString("PATH_OUT",pathIn);
		String filter=cfg.getString("FILTER");
		//String fileName="fvcirscen1m";
		
		ScenarioBinFileExtractor ScenarioBinFileReader= new ScenarioBinFileExtractor(pathIn,pathOut, aod,filter);
		ScenarioBinFileReader.process();

	}

	private void process() throws IOException, FileParserException, InterruptedException, CalendarException
	{
		RunningTime rt = new RunningTime();
		rt.start();
		log.info("start");
		

		if (filter!=null)
			rfFilter=filter.split(",");
		
		CcrConfigGeneratorConfig ccr = new CcrConfigGeneratorConfig();
	
		
		// Retrieve number of scenarios
		CcrConfigReader ccrR = new CcrConfigReader(pathIn +"/"+ ReplaceUtils.replaceAod(ccr.getCcrConfigFileName(),aod));
		ccrR.process();
		int numbScenarios = ccrR.getCcfCfg().getNumOfPaths();
		
		GridPointFileReader gpReader = new GridPointFileReader(aod, pathIn+"/"+ ReplaceUtils.replaceAod(ccr.getScheduleFileName365(),aod));
		gpReader.process();
		List<GridPoint> gridPointList = gpReader.getGridPoints();
		
		
		String[] rowNames = new String[numbScenarios + 1];
		for (int i = 0; i < rowNames.length; i++)
		{
			Formatter formatter = new Formatter();
			rowNames[i] = formatter.format("%06d", i).toString();
		}
		
		
		TextFileReader textFileReader = new TextFileReader((pathIn +"/"+ ReplaceUtils.replaceAod(ccr.getRfListFileName(),aod)));
		textFileReader.process();
		String[] rfNames = textFileReader.get();
		ArrayList<String> rfNamesFiltred= new  ArrayList<String>();
		for(String rf: rfNames){
			if(rfFilter!=null){
				for(String rfF:rfFilter){
					if(rf.startsWith(rfF))
						rfNamesFiltred.add(rf);					
				}
			}
			else
			{

				rfNamesFiltred.add(rf);
			}
		}
		
		String[] rfNamesF=rfNamesFiltred.toArray(new String[rfNamesFiltred.size()] );
		
		for(GridPoint gp : gridPointList){
			String fileName= gp.getName();
			RunningTime rtInner = new RunningTime();
			rtInner.start();
			log.info("read: "+ fileName);
			Mat mat = Mat.readArray("fv", pathIn + "/" + fileName, 0, rfNames.length);
			Sheet sheet = new Sheet("sheet", rowNames, rfNames, mat);	
			sheet=sheet.extract("", rfNamesF);
			sheet.writeAsCsvFile(pathIn+"/"+fileName+"["+filter+"].csv", ",");

			rtInner.stop();
			log.info("end Write: "+ fileName+ " "+ rtInner.getElapsedMillisecs());
		}

		rt.stop();
		log.info("end "+rt.getElapsedMillisecs());
	}

}
